import re
import os
import sys
import logging



def print_hi(name):
    # 在下面的代码行中使用断点来调试脚本。
    print(f'Hi, {name}')  # 按 Ctrl+F8 切换断点。

#定义1个生成器
def file_line_generator(file_name):
    with open(file_name, 'r', encoding='utf-8') as file:
        # for line in file:
        #     yield line.strip()
        for line_num,line in enumerate(file,start=0):
            yield line_num,line.strip()

#正则匹配
def regex_match(line):
    #match_point = re.match('^(\s*)(?P<type>Startpoint|EndPoint)\s*:\s*(?P<module_sub1>[A-Z0-9_]+)(/)(?P<module_sub2>[A-Z0-9_]+)*', line)
    match_point = re.match('^(\s*)(?P<type>Startpoint|Endpoint)\s*:\s*(?P<module_sub1>[A-Z0-9_]+)(/)(?P<module_sub2>[A-Z0-9_]+)*', line)
    if (match_point):
        type= match_point.groupdict()['type']
        module_sub1=match_point.groupdict()['module_sub1']
        module_sub2 = match_point.groupdict()['module_sub2']
        return type,module_sub1,module_sub2
    else:
        match_time = re.match('^(\s*)(?P<type>data\s*arrival\s*time)(\s+)(?P<value>\d+\.\d+)', line)
        if (match_time):
            # type= match_time.groupdict()['type']
            type = 'data arrival time'
            value = match_time.groupdict()['value']
            return type,value
        else:
            match_slack = re.match('^(\s*)(?P<type>\s*slack)(\s*\([A-W]+\)\s*)(?P<value>-?\d+\.\d+)', line)
            if (match_slack):
                # type= match_slack.groupdict()['type']
                type = 'slack'
                value = match_slack.groupdict()['value']
                return type,value
            else:
                return None
#写入对应的子模块rpt
def submodule1_append(sub1,sub2,lines):
    if sub1 == sub2:
        filename=f"{sub1}.rpt"
    else:
        filename=f"{sub1}2{sub2}.rpt"
    with open(filename,'a', encoding='utf-8') as file:
            for item in lines:
                file.write(item)
                file.write('\n')


# 按装订区域中的绿色按钮以运行脚本。
if __name__ == '__main__':
    # 获取当前脚本所在的绝对路径
    script_dir = os.path.dirname(os.path.abspath(__file__))
    # 将工作目录切换到脚本所在目录
    os.chdir(script_dir)
    print(f"当前工作目录已设置为: {os.getcwd()}")

    #print_hi('PyCharm')
    match_result=()
    block_flag=''
    block_ctx=[]
    start_module_sub1=''
    start_module_sub2 = ''
    end_module_sub1 = ''
    end_module_sub2 = ''
    data_arrival_time=0.0
    slack=0.0
    # 使用生成器逐行处理文件
    for line_num,line in file_line_generator('top.rpt.txt'):
        print(line)
        match_result=regex_match(line)
        if match_result:
            match_result_length=len(match_result)
        else:
            match_result_length=0
        if match_result_length==3:#startpoint、endpoint
            type,module_sub1,module_sub2=match_result
            if type=='Startpoint':
                block_flag='start'
                start_module_sub1=module_sub1
                start_module_sub2=module_sub2
                block_ctx.clear()
                block_ctx.append(line)
            elif type=='Endpoint':
                type, module_sub1, module_sub2 = match_result
                end_module_sub1 = module_sub1
                end_module_sub2 = module_sub2
                block_ctx.append(line)
            else:
                logging.warning(format(line_num)+"行解析失败，返回值个数为3，但既不是startpoint，也不是endpoint.")
                block_ctx.append(line)
        elif match_result_length==2:
            type,value=match_result
            if type=='data arrival time':
                data_arrival_time=value
                block_ctx.append(line)
            elif type=='slack':
                block_flag='end'
                slack=value
                block_ctx.append(line)
                submodule1_append(start_module_sub1, end_module_sub1, block_ctx)
                #block_ctx.clear()
            else:
                logging.warning(format(line_num) + "行解析失败，返回值个数为2，但既不是data arrival time，也不是slack.")
                block_ctx.append(line)
        elif block_flag=='start':
            block_ctx.append(line)
        else:
            continue
    logging.info(format(line_num) + "已处理完毕")








